<template>
  <div class="publish">
    <div class="form">
      <el-form
        :model="formData"
        :rules="formRules"
        label-width="80px"
        size="large"
        ref="formRef"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动内容" prop="description">
          <editor v-model="formData.description"></editor>
        </el-form-item>
        <el-form-item label="活动时间" prop="description">
          <el-date-picker
            v-model="formData.date_time"
            type="datetimerange"
            range-separator="To"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            size="default"
          />
        </el-form-item>
        <el-form-item label="选择社团" prop="club_id">
          <el-select
            v-model="formData.club_id"
            filterable
            placeholder="选择社团"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参与人数" prop="registration_limit">
          <el-input-number
            v-model="formData.registration_limit"
            :min="1"
            :max="1000"
          />
        </el-form-item>

        <el-form-item
          label="活动封面"
          label-width="100px"
          prop="background_image_url"
        >
          <template #default>
            <el-upload
              class="avatar-uploader"
              :action="`${BASE_URL}/file/event/picture`"
              :headers="{
                Authorization: loginStore.token // 假设 token 是从 Vuex 中获取的
              }"
              accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              name="event-picture"
            >
              <img
                v-if="formData.background_image_url"
                :src="formData.background_image_url"
                class="avatar"
              />

              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <el-button @click="publish" class="btn" type="primary" size="large"
      >发布</el-button
    >
  </div>
</template>
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'

import useLoginStore from '@/store/login/login'
import useEventStore from '@/store/main/event/event'
import useClubStore from '@/store/main/club/club'

import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules, ElForm, UploadProps } from 'element-plus'
import { BASE_URL } from '@/service/config'
import Editor from './c-cpns/editor.vue'
import { storeToRefs } from 'pinia'
import { getRole } from '@/utils/handle-role'

const loginStore = useLoginStore()
const eventStore = useEventStore()
const clubStore = useClubStore()

const formData = reactive<any>({
  title: '',
  description: '',
  date_time: [],
  background_image_url: '',
  registration_limit: 0,
  club_id: ''
})
const role = ref(getRole())

const formRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  date_time: [{ required: true, message: '请输入活动时间', trigger: 'blur' }],
  background_image_url: [
    { required: true, message: '请上传封面图', trigger: 'blur' }
  ],
  club_id: [{ required: true, message: '请输入社团名字', trigger: 'blur' }],
  registration_limit: [
    { required: true, message: '请输入参与人数', trigger: 'blur' }
  ]
}
const formRef = ref<InstanceType<typeof ElForm>>()
// 获取社团信息
const { clubsList } = storeToRefs(clubStore)
if (role.value === 2) {
  clubStore.getClubsListAction(1000, 0, 'approved')
} else {
  clubStore.getClubByUserIdAction()
}
const options = computed(() => {
  return clubsList.value.map((item) => ({
    label: item.name,
    value: item.id
  }))
})

// 上传图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  console.log(response)
  formData.background_image_url = response.data.url
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 发布活动
function publish() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      formData.start_date = formData.date_time[0]
      formData.end_date = formData.date_time[1]
      ElMessageBox.confirm(`确定发布这个活动吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(formData)
        await eventStore.publishEventAction(formData)
        ElMessage({
          type: 'success',
          message: '发布活动成功'
        })
        formRef.value?.resetFields()
      })
    } else {
      ElMessage({
        type: 'error',
        message: '请输入信息'
      })
    }
  })
}
</script>

<style lang="less">
.publish {
  margin-top: 10px;
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .btn {
    width: 150px;
  }
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload {
    background-color: #f0f2f5;
    border: 1px border red;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: black;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
